package 青岛远业

import java.io.DataOutputStream;
import java.text.SimpleDateFormat
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import com.alibaba.fastjson.JSON;
import java.util.UUID;

def execute(data, dlzt) {
    println "-------------------------调用服务接口-------------------------"
    long startTime = System.currentTimeMillis();    //获取开始时间
    try {
        if (data == null || data.size() == 0) {
            return ["state": 0, "Ascript": "没有查询参数" + data]
        }
        if (!data.get("info")) {
            return ["state": 0, "Ascript": "参数中没有info信息" + data]
        }
        //请求信息
        def info = data.get("info")
        if (info.get("account") == null) {
            return ["state": 0, "Ascript": "缺少帐套信息(account)     请求JSON" + data]
        }

        def conn
        try {
            conn = groovy.sql.Sql.newInstance(dlzt.hqcon(1))
            //根据帐套号获取帐套信息
            def accountMap = conn.firstRow("select * from YZ_TM_Account where account='" + info.get("account") + "'")
            if (accountMap == null) {
                return ["state": 0, "Ascript": "帐套" + info.get("account") + "未查询到该帐套(account)     请求JSON" + data]
            }
            HQMHttps.account = accountMap
        } catch (Exception e) {
            e.printStackTrace();
            return ["state": 0, "Ascript": "帐套信息查询错误"]
        } finally {
            if (conn != null) {
                conn.close()
            }
        }


        def reMap = TransVoucherOpenApi_Create(data, dlzt)
        println "返回信息"
        println reMap
        if (reMap.get("state") == 1) {
            long endTime = System.currentTimeMillis();    //获取结束时间
            System.out.println(info.get("type") + ":" + (endTime - startTime) + " ms");    //输出程序运行时间
            return ["state": 1, "Ascript": reMap.get("Ascript"), "data": reMap.get("data")]
        } else {
            return ["state": 0, "Ascript": reMap.get("Ascript")]
        }

    } catch (Exception e) {
        e.printStackTrace();
        return ["state": 0, "Ascript": "请求参数错误,请检查"]
    }
}
/*
 * 创建人：胡勤明
 * 创建时间：2022-08-30
 * 最后一次修改时间：2024-07-22
 * 方法作用：无来源生成其他入库单
 * */
// 你按照这个类的调用方式写就行。具体接口配置是不是不需要你来管理

def TransVoucherOpenApi_Create(data, dlzt) {
    def conn
    try {
        conn = new groovy.sql.Sql(dlzt.hqcon(2))
        def headUpMap = data.get("head")
        if (headUpMap == null || headUpMap.size() == 0) {
            return ["state": 0, "Ascript": "请求参数中表头不能为空"]
        }
        def headMap = [:]
        try {
            //表头
            for (def key : headUpMap.keySet()) {
                headMap.put(key.toLowerCase(), headUpMap.get(key))
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ["state": 0, "Ascript": "请检查表头数据格式"]
        }
        def bodyUpList = data.get("body")
        if (bodyUpList == null || bodyUpList.size() == 0) {
            return ["state": 0, "Ascript": "请求参数中表体不能为空"]
        }
        def bodyList = []
        try {
            //表体转换参数大小写
            for (def bodyUpMap : bodyUpList) {
                def bodyMap = [:]
                for (def key : bodyUpMap.keySet()) {
                    bodyMap.put(key.toLowerCase(), bodyUpMap.get(key))
                }
                bodyList.add(bodyMap)
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ["state": 0, "Ascript": "请检查表体数据格式"]
        }


        //时间
        java.text.SimpleDateFormat dqdate = new java.text.SimpleDateFormat("yyyy-MM-dd")
        def dqdateString = dqdate.format(new Date())
        java.text.SimpleDateFormat dqdatetime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        def dqdatetimeString = dqdatetime.format(new Date())


        //外部结构
        def dto = ["dto": [:]]

        //headMap=data.get("head")

        /*
         * 
         * 设置默认值
         * 
         * */

        //单据类型
        if (headMap.get("vouchertype") == null) {
            headMap.put("vouchertype", "ST1004")
        }
        //业务类型 取值范围：业务类型编码
        //07 受赠
        //08 盘盈
        //12 受赠退库
        //13 其他
        //14 其他退库
        if (headMap.get("busitype") == null) {
            headMap.put("busitype", "13")
        }
        //单据日期
        if (headMap.get("voucherdate") == null) {
            headMap.put("voucherdate", dqdateString)
        }
        if (headMap.get("externalcode") == null) {
            //外部唯一值
            def uuid = getUUid()
            headMap.put("externalcode", uuid)
        }


        /*
         * 
         * 验证必输
         * 
         * */
//        def HeadNotNUllMap = ["partner": "供应商"]
//        for (def key : HeadNotNUllMap.keySet()) {
//            if (headMap.get(key) == null || "".equals(headMap.get(key))) {
//                return ["state": 0, "Ascript": "表头" + key + "(" + HeadNotNUllMap.get(key) + ")不能为空"]
//            }
//        }
//
//        def outwarehouseIt = conn.firstRow("select * from [" + bainuo.bainuo.HQMHttps.account.accountdatabase + "]..AA_Warehouse where code='" + headMap.get("outwarehouse") + "'")
//        if (outwarehouseIt == null) {
//            return ["state": 0, "Ascript": "调出仓库编码为查询到请检查(outwarehouse)"]
//        }
//        def inwarehouseIt = conn.firstRow("select * from [" + bainuo.bainuo.HQMHttps.account.accountdatabase + "]..AA_Warehouse where code='" + headMap.get("inwarehouse") + "'")
//        if (inwarehouseIt == null) {
//            return ["state": 0, "Ascript": "调入仓库编码为查询到请检查(inwarehouse)"]
//        }
        /*
         * 
         * 对象转换
         * 
         * */
        def HeadToObject = ["vouchertype": "单据类型", "busitype": "业务类型",  "rdstyle": "入库类别",  "clerk": "经办人",  "project": "项目信息",  "department": "部门"]
        for (def key : HeadToObject.keySet()) {
            if (headMap.get(key) != null) {
                headMap.put(key, ["code": headMap.get(key)])
            }
        }
        //将表头结构赋值
        dto.get("dto").putAll(headMap)

        //表体必输
        def BodyNotNUllMap = ["inventory": "存货编码", "quantity": "数量"]

        //表体结构
        def RDRecordDetails = []
        //表体参数循环赋值
        for (int i = 0; i < bodyList.size(); i++) {
            def bodyMap = bodyList.get(i)
            if (bodyMap == null || bodyMap.size() == 0) {
                return ["state": 0, "Ascript": "表体数据不能为空"]
            }



//            if (headMap.get("warehouse") == null && bodyMap.get("warehouse") == null) {
//                return ["state": 0, "Ascript": "表头和表体的仓库(warehouse)不能同时为空"]
//            }
            /*
             * 
             * 设置默认值
             * 
             * */


            /*
             * 
             * 验证必输
             * 
             * */
//            for (def key : BodyNotNUllMap.keySet()) {
//                if (bodyMap.get(key) == null || "".equals(bodyMap.get(key))) {
//                    return ["state": 0, "Ascript": "表体中第" + (i + 1) + "行" + key + "(" + BodyNotNUllMap.get(key) + ")不能为空"]
//                }
//            }
            /*
             * 
             * 对象转换
             * 
             * */
            def BodyToObject = ["inventory": "存货", "warehouse": "仓库", "inventory_expiredunit":"保质期单位","project": "项目信息"]
            for (def key : BodyToObject.keySet()) {
                if (bodyMap.get(key) != null) {
                    bodyMap.put(key, ["code": bodyMap.get(key)])
                }
            }

            if (bodyMap.get("unit") != null) {
                bodyMap.put("unit", ["Name": bodyMap.get("unit")])
            }
            if (bodyMap.get("unit2") != null) {
                bodyMap.put("unit2", ["Name": bodyMap.get("unit2")])
            }
        }
        RDRecordDetails.addAll(bodyList)
        dto.get("dto").put("RDRecordDetails", RDRecordDetails)

        def reMap = HQMHttps.httpFWToMap("tplus/api/v2/OtherReceiveOpenApi/Create", dto)
        if ("0".equals(reMap.get("code").toString())) {
            return ["state": 1, "Ascript": "其他入库单插入成功,单据号为：" + reMap.get("data").get("Code"), "data": reMap.get("data")]
        } else {
            return ["state": 0, "Ascript": reMap.get("message") + "错误码为:" + reMap.get("code") + "   错误回答为" + reMap.get("data")]
        }
    } catch (Exception e) {
        e.printStackTrace();
        return ["state": 0, "Ascript": "无来源其他入库单插入错误"]
    } finally {
        if (conn != null) {
            conn.close()
        }
    }
}


class HQMHttps {
    public static HashMap<String, Object> account = new HashMap<String, Object>();

    public HQMHttps() {
    }

    public HQMHttps(HashMap<String, Object> account) {
        this.account = account;
    }
    //进行Http请求
    public static List httpFWToList(String url, Map mapdata) {
        String json = JSON.toJSONString(mapdata);
        //        println "请求JSON"
        //        println json
        //PrintWriter out = null;
        DataOutputStream out
        BufferedReader ins = null;
        String result = "";
        try {
            URL realUrl = new URL("https://openapi.chanjet.com/" + url);
            // 打开和URL之间的连接
            HttpURLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            // 设置通用的请求属性
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Transfer-Encoding", "chunked");
            conn.setRequestProperty("Keep-Alive", "chunked");
            conn.setRequestProperty("appKey", account.get("appKey"));
            conn.setRequestProperty("appSecret", account.get("appSecret"));
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("openToken", account.get("access_token"));
            conn.connect();
            // 获取HttpURLConnection对象对应的输出流
            //            out = new PrintWriter(conn.getOutputStream());
            //            // 发送请求参数
            //            out.print(json);
            //            // flush输出流的缓冲
            //            out.flush();
            out = new DataOutputStream(conn.getOutputStream());
            if (!"".equals(json)) {
                //out.writeBytes(json);
                out.write(json.getBytes("UTF-8"));
            }
            out.flush();
            out.close();

            // 定义BufferedReader输入流来读取URL的响应
            //ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            if (conn.getResponseCode() == 200) {
                ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                ins = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }
            String line;
            while ((line = ins.readLine()) != null) {
                result += line;
            }
            return JSON.parseObject(result, List.class);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            System.out.println("[POST请求]向地址：" + url + " 发送数据：" + json + " 发生错误!" + result + "JSON结束");
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        return null;
    }
    //进行Http请求
    public static Map httpFWToMap(String url, Map mapdata) {
        String json = JSON.toJSONString(mapdata);
        println "请求JSON"
        println json
        //PrintWriter out = null;
        DataOutputStream out
        BufferedReader ins = null;
        String result = "";
        try {
            URL realUrl = new URL("https://openapi.chanjet.com/" + url);
            // 打开和URL之间的连接
            HttpURLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            // 设置通用的请求属性
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Transfer-Encoding", "chunked");
            conn.setRequestProperty("Keep-Alive", "chunked");
            conn.setRequestProperty("appKey", account.get("appKey"));
            conn.setRequestProperty("appSecret", account.get("appSecret"));
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("openToken", account.get("access_token"));
            conn.connect();
            // 获取HttpURLConnection对象对应的输出流
            //            out = new PrintWriter(conn.getOutputStream());
            //            // 发送请求参数
            //            out.print(json);
            //            // flush输出流的缓冲
            //            out.flush();
            out = new DataOutputStream(conn.getOutputStream());
            if (!"".equals(json)) {
                //out.writeBytes(json);
                out.write(json.getBytes("UTF-8"));
            }
            out.flush();
            out.close();


            // 定义BufferedReader输入流来读取URL的响应
            //            ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            if (conn.getResponseCode() == 200) {
                ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                ins = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }

            String line;
            while ((line = ins.readLine()) != null) {
                result += line;
            }
            return JSON.parseObject(result, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[POST请求]向地址：" + url + " 发送数据：" + json + " 发生错误!" + result + "JSON结束");
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        return null;
    }

    public static String httpFWToJson(String url, Map mapdata) {
        String json = JSON.toJSONString(mapdata);
        //        println "请求JSON"
        //        println json
        //PrintWriter out = null;
        DataOutputStream out
        BufferedReader ins = null;
        String result = "";
        try {
            URL realUrl = new URL("https://openapi.chanjet.com/" + url);
            // 打开和URL之间的连接
            HttpURLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            // 设置通用的请求属性
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Transfer-Encoding", "chunked");
            conn.setRequestProperty("Keep-Alive", "chunked");
            conn.setRequestProperty("appKey", account.get("appKey"));
            conn.setRequestProperty("appSecret", account.get("appSecret"));
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("openToken", account.get("access_token"));
            conn.connect();
            // 获取HttpURLConnection对象对应的输出流
            //            out = new PrintWriter(conn.getOutputStream());
            //            // 发送请求参数
            //            out.print(json);
            //            // flush输出流的缓冲
            //            out.flush();
            out = new DataOutputStream(conn.getOutputStream());
            if (!"".equals(json)) {
                //out.writeBytes(json);
                out.write(json.getBytes("UTF-8"));
            }
            out.flush();
            out.close();

            // 定义BufferedReader输入流来读取URL的响应
            //            ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            if (conn.getResponseCode() == 200) {
                ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                ins = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }
            String line;
            while ((line = ins.readLine()) != null) {
                result += line;
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[POST请求]向地址：" + url + " 发送数据：" + json + " 发生错误!" + result + "JSON结束");
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        return null;
    }
}

def getUUid() {
    String preUuid = UUID.randomUUID().toString();
    return preUuid
}